from datetime import datetime
def calculate_statistics(data):
    """
    统一计算所有统计指标
    返回包含所有统计结果的字典
    """
    if not data:
        return {
            "totalCommunities": 0,
            "totalDry": 0.0,
            "totalWet": 0.0,
            "dryTop5": [],
            "wetTop5": [],
            "vehicleTop5": [],
            "streetTop5": []
        }

    # 1. 总计统计
    total_communities = len(data)
    total_dry = round(sum(item['dryWeight'] for item in data), 2)
    total_wet = round(sum(
        item['wetWeight'] + item['restaurantWeight'] + item['foodWeight']
        for item in data
    ), 2)

    # 2. 干垃圾前五
    dry_top5 = sorted(data, key=lambda x: x['dryWeight'], reverse=True)[:5]
    dry_list = [
        {"communityName": c['communityName'], "dryWeight": c['dryWeight']}
        for c in dry_top5
    ]

    # 3. 湿垃圾前五（含餐厨/厨余）
    wet_data = [
        {
            "communityName": item['communityName'],
            "totalWet": round(item['wetWeight'] + item['restaurantWeight'] + item['foodWeight'], 2)
        }
        for item in data
    ]
    wet_list = sorted(wet_data, key=lambda x: x['totalWet'], reverse=True)[:5]

    # 4. 车辆使用前五
    vehicle_data = [
        {
            "communityName": item['communityName'],
            "vehicleCount": len(item['vehicles']) if item['vehicles'] else 0
        }
        for item in data
    ]
    vehicle_list = sorted(vehicle_data, key=lambda x: x['vehicleCount'], reverse=True)[:5]

    # 5. 街道小区数前五
    street_count = {}
    for item in data:
        street = item['streetName']
        if street:
            street_count[street] = street_count.get(street, 0) + 1

    street_list = [
        {"streetName": name, "communityCount": count}
        for name, count in sorted(street_count.items(), key=lambda x: x[1], reverse=True)[:5]
    ]

    return {
        "清运小区数量": total_communities,
        "清运干垃圾总量": total_dry,
        "清运湿垃圾总量": total_wet,
        "干垃圾清运小区Top5": dry_list,
        "湿垃圾清运小区Top5": wet_list,
        "清运车辆使用辆小区Top5": vehicle_list,
        "街道清运小区数Top5": street_list
    }


def calculate_street_stats(data, street_name):
    """
    统计特定街道的垃圾清运数据

    参数:
        data: 原始数据列表，包含街道、小区、垃圾量等信息
        street_name: 要统计的街道名称

    返回:
        包含该街道统计结果的字典
    """
    # 首先筛选出指定街道的数据
    street_data = [item for item in data if item.get("街道名称") == street_name]

    if not street_data:
        return {
            "街道名称": street_name,
            "小区数量": 0,
            "干垃圾总量": 0.0,
            "湿垃圾总量": 0.0,
            "小区列表": [],
            "message": f"未找到{street_name}的数据"
        }

    # 1. 总计统计
    unique_communities = set(item["小区名称"] for item in street_data)
    community_count = len(unique_communities)

    total_dry = sum(item.get("干垃圾量", 0) for item in street_data)
    total_wet = sum(
        item.get("湿垃圾量", 0) + item.get("厨余垃圾量", 0) + item.get("餐厨垃圾量", 0) for item in street_data)

    # 2. 按小区聚合数据
    community_stats = {}
    for item in street_data:
        community_name = item["小区名称"]
        if community_name not in community_stats:
            community_stats[community_name] = {
                "小区名称": community_name,
                "干垃圾量": 0,
                "湿垃圾总量": 0,  # 湿垃圾+厨余垃圾+餐厨垃圾
                "经度": item.get("小区y坐标", 0),  # 注意：数据中xy和经纬度似乎有混淆
                "纬度": item.get("小区x坐标", 0)
            }

        # 累加各类垃圾量
        community_stats[community_name]["干垃圾量"] += item.get("干垃圾量", 0)
        community_stats[community_name]["湿垃圾总量"] += (
                item.get("湿垃圾量", 0) +
                item.get("厨余垃圾量", 0) +
                item.get("餐厨垃圾量", 0)
        )

    # 将字典转为列表
    communities_list = list(community_stats.values())

    # 3. 生成各种Top5榜单
    # 干垃圾量前五小区
    dry_top5 = sorted(communities_list, key=lambda x: x["干垃圾量"], reverse=True)[:5]

    # 湿垃圾量前五小区
    wet_top5 = sorted(communities_list, key=lambda x: x["湿垃圾总量"], reverse=True)[:5]

    # 垃圾总量前五小区
    total_top5 = sorted(
        communities_list,
        key=lambda x: x["干垃圾量"] + x["湿垃圾总量"],
        reverse=True
    )[:5]

    # 4. 计算该街道占全区的百分比
    all_dry = sum(item.get("干垃圾量", 0) for item in data)
    all_wet = sum(
        item.get("湿垃圾量", 0) + item.get("厨余垃圾量", 0) + item.get("餐厨垃圾量", 0)
        for item in data
    )

    dry_percentage = round((total_dry / all_dry * 100) if all_dry > 0 else 0, 2)
    wet_percentage = round((total_wet / all_wet * 100) if all_wet > 0 else 0, 2)

    # 5. 构建返回结果
    return {
        "街道名称": street_name,
        "小区数量": community_count,
        "干垃圾总量(kg)": total_dry,
        "湿垃圾总量(kg)": total_wet,  # 包含湿垃圾、厨余垃圾和餐厨垃圾
        # "干垃圾占全区比例": f"{dry_percentage}%",
        # "湿垃圾占全区比例": f"{wet_percentage}%",
        "干湿垃圾比例": f"{round(total_dry / total_wet, 2) if total_wet > 0 else '只有干垃圾'}",

        "干垃圾清运量Top5": [{
            "小区名称": item["小区名称"],
            "干垃圾量(kg)": item["干垃圾量"]
        } for item in dry_top5],

        "湿垃圾清运量Top5": [{
            "小区名称": item["小区名称"],
            "湿垃圾量(kg)": item["湿垃圾总量"]
        } for item in wet_top5],

        "垃圾清运总量Top5": [{
            "小区名称": item["小区名称"],
            "总量(kg)": item["干垃圾量"] + item["湿垃圾总量"]
        } for item in total_top5],

        # 全部小区列表，带详细数据
        # "小区详情": [
        #     {
        #         "小区名称": item["小区名称"],
        #         "干垃圾量(kg)": item["干垃圾量"],
        #         "湿垃圾量(kg)": item["湿垃圾总量"],
        #         "位置": [item["经度"], item["纬度"]]
        #     }
        #     for item in communities_list
        # ]
    }


def calculate_community_stats(data, community_name):
    """
    统计特定小区的垃圾清运数据

    参数:
        data: 原始数据列表，包含街道、小区、垃圾量等信息
        community_name: 要统计的小区名称

    返回:
        包含该小区统计结果的字典
    """
    # 筛选出指定小区的数据
    community_data = [item for item in data if item.get("小区名称") == community_name]

    if not community_data:
        return {
            "小区名称": community_name,
            "清运点数量": 0,
            "干垃圾总量": 0,
            "湿垃圾总量": 0,
            "message": f"未找到{community_name}的数据"
        }

    # 1. 提取小区基本信息(取第一条记录的信息)
    first_record = community_data[0]
    street_name = first_record.get("街道名称", "未知街道")
    community_x = first_record.get("小区x坐标")
    community_y = first_record.get("小区y坐标")

    # 2. 计算总量数据
    total_dry = sum(item.get("干垃圾量", 0) for item in community_data)
    total_wet_kitchen = sum(item.get("湿垃圾量", 0) for item in community_data)
    total_food_waste = sum(item.get("厨余垃圾量", 0) for item in community_data)
    total_restaurant_waste = sum(item.get("餐厨垃圾量", 0) for item in community_data)

    # 湿垃圾总量(所有湿垃圾类型总和)
    total_wet_all = total_wet_kitchen + total_food_waste + total_restaurant_waste

    # 3. 提取所有清运点信息，将经纬度保留两位小数进行判断
    collection_points = []
    unique_points = set()  # 用于去重

    for item in community_data:
        # 获取经纬度并保留两位小数
        longitude = item.get("清运点经度")
        latitude = item.get("清运点纬度")

        # 将经纬度保留两位小数用于判断是否为同一点
        rounded_lng = round(longitude, 2) if longitude is not None else None
        rounded_lat = round(latitude, 2) if latitude is not None else None

        # 创建去重用的点位键
        point_key = f"{rounded_lng}_{rounded_lat}"

        if point_key not in unique_points:
            unique_points.add(point_key)
            # 在添加到结果列表时仍使用原始精度
            collection_points.append({
                "经度": longitude,
                "纬度": latitude
            })

    # 4. 分析记录时间分布(如果数据中有时间字段)
    # 注意：您提供的数据样例中没有时间字段，如果实际数据中有，可以取消注释下面的代码
    #
    # from collections import Counter
    # dates = [item.get("日期", "未知日期") for item in community_data]
    # date_distribution = dict(Counter(dates))

    # 5. 构建返回结果
    result = {
        "小区名称": community_name,
        "所属街道": street_name,
        "位置坐标": {
            "x坐标": community_x,
            "y坐标": community_y
        },
        "清运统计": {
            "记录数量": len(community_data),
            "清运点数量": len(collection_points),
            "垃圾总量(kg)": total_dry + total_wet_all,
            "干垃圾总量(kg)": total_dry,
            "湿垃圾总量(kg)": total_wet_all,
            "垃圾类型明细": {
                "干垃圾(kg)": total_dry,
                "湿垃圾(kg)": total_wet_kitchen,
                "厨余垃圾(kg)": total_food_waste,
                "餐厨垃圾(kg)": total_restaurant_waste
            },
            "干湿比例": round(total_dry / total_wet_all, 2) if total_wet_all > 0 else "∞"
        },
        "清运点列表": collection_points
    }

    # 如果有日期分布数据，添加到结果中
    # if 'date_distribution' in locals():
    #     result["日期分布"] = date_distribution

    return result